package com.ganbo.controller;

import com.ganbo.common.entity.User;
import com.ganbo.common.service.IUserService;
import com.ganbo.common.utils.Result;
import com.ganbo.dto.AddUserReq;
import com.ganbo.service.JedisService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Created by ganbo on 2019/6/24.
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {


    @Autowired
    IUserService userService;
    @Autowired
    JedisService jedisService;

    @GetMapping("/list")
    public List<User> list() {
        List<User> list = userService.list();
        return list;
    }

    @PostMapping("/add")
    public Result add(@RequestBody AddUserReq req) {
        //手动参数校验
        String bussSeqNo = req.getBussSeqNo();
        if (StringUtils.isBlank(bussSeqNo)) {
            return Result.fail("流水号不能为空");
        }

        String lockKey = String.format("lock:customerRegister:%s", bussSeqNo);
        System.out.println("lockKey=====>" + lockKey);
        boolean isLocked = jedisService.tryLock(lockKey);
        System.out.println("isLocked======>" + isLocked);
        if (isLocked) {
            try {
                User user = new User();
                BeanUtils.copyProperties(req, user);
                userService.save(user);
                Thread.sleep(4000); //模拟网络延迟和本地操作时间
            } catch (Exception e) {
                log.error("添加用户出错:", e);
                return Result.fail("保存用户失败");
            } finally {
                jedisService.removeLock(lockKey);
            }

        } else {
            return Result.fail("操作失败,同一个流水号,请不要重复提交.");
        }

        return Result.success("添加成功");

    }

}
